package com.android.nodejs.livejs.activities;

import java.io.BufferedWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.net.SocketTimeoutException;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.android.nodejs.livejs.MyApplication;
import com.android.nodejs.livejs.R;
import com.android.nodejs.livejs.adapters.SearchFriendsAdapter;
import com.android.nodejs.livejs.base.BaseFragment;
import com.android.nodejs.livejs.constants.AddMessageConstants;
import com.android.nodejs.livejs.constants.DisplayConstants;
import com.android.nodejs.livejs.models.User;
import com.android.nodejs.livejs.utils.CommonUtil;

public class InvitationFragment extends BaseFragment {
    private ListView mListViewFriendSearch;
    private ListView mListViewFriendRequest;
    private View mView;
    private Button btnAddFriend;
    private Button btnFriendRequest;
    private Button btnSearchFriends;
    private RelativeLayout rlAddFriend;
    private RelativeLayout rlFriendsRequest;
    private EditText edtSearch;

    private boolean isPressAddFriendButton = false;
    private boolean isPressFriendsRequestButton = false;

    private ProgressDialog progressDialog;
    private int numSelectedInListView;
    private List<User> users = new ArrayList<User>();
    private SearchFriendsAdapter friendRequestAdapter;

    private int user_id;
    private int friend_id;
    private String fullName;
    private String email;
    private String birthday;
    private int gender;
    private String strGender;
    private String status;
    private String last_status;

    @Override
    public void inits() {
        // nothing
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        mView = inflater.inflate(R.layout.fragment_invitations, container, false);
        // register broad cast
        IntentFilter filterMessage = new IntentFilter("SEARCH_FRIENDS");
        getActivity().registerReceiver(new MessageBroadCastReceiver(), filterMessage);
        IntentFilter filter = new IntentFilter("NOTIFY_FRIEND_REQUEST");
        getActivity().registerReceiver(new MessageBroadCastReceiver(), filter);
        IntentFilter filterAc = new IntentFilter("ACCEPT_FRIEND_REQUEST");
        getActivity().registerReceiver(new MessageBroadCastReceiver(), filterAc);
        return mView;
    }

    @Override
    public void initComponents(View view) {
        mListViewFriendSearch = (ListView) view.findViewById(R.id.listFriendsSearch);
        mListViewFriendRequest = (ListView) view.findViewById(R.id.listFriendsRequest);
        friendRequestAdapter = new SearchFriendsAdapter(getActivity(), MyApplication.LIST_FRIENDS_REQUEST);
        mListViewFriendRequest.setAdapter(friendRequestAdapter);
        mListViewFriendRequest.setOnItemLongClickListener(new OnItemLongClickListener() {
            public boolean onItemLongClick(AdapterView<?> adapter, View v, int position, long id) {
                numSelectedInListView = position;
                AlertDialog.Builder dialog = new AlertDialog.Builder(getActivity());
                dialog.setItems(new String[] { "Accept", "Don't accept", "View Profile" }, new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        user_id = MyApplication.USER_CURRENT.getId();
                        friend_id = ((User) mListViewFriendRequest.getAdapter().getItem(numSelectedInListView)).getId();
                        fullName = ((User) mListViewFriendRequest.getAdapter().getItem(numSelectedInListView)).getFullName();
                        email = ((User) mListViewFriendRequest.getAdapter().getItem(numSelectedInListView)).getEmail();
                        birthday = CommonUtil.dateToString(((User) mListViewFriendRequest.getAdapter().getItem(
                                numSelectedInListView)).getBirthday());
                        gender = ((User) mListViewFriendRequest.getAdapter().getItem(numSelectedInListView)).getGender();
                        strGender = gender == 1 ? "Male" : "Female";
                        status = ((User) mListViewFriendRequest.getAdapter().getItem(numSelectedInListView)).getStatus();
                        last_status = ((User) mListViewFriendRequest.getAdapter().getItem(numSelectedInListView)).getLastStatus();
                        if ("null".equals(status)) {
                            status = "No status";
                        }
                        switch (which) {
                            case 0:
                                progressDialog = ProgressDialog.show(getActivity(), "", "Adding friend...");
                                try {
                                    BufferedWriter w = new BufferedWriter(new OutputStreamWriter(MyApplication.OS_CURRENT));
                                    if (user_id == friend_id) {
                                        Message msg = toastHandler.obtainMessage(3);
                                        toastHandler.sendMessage(msg);
                                    } else {
                                        w.write(AddMessageConstants.ACCEPT_FRIEND_REQUEST);
                                        w.write(user_id + "!!" + friend_id);
                                        w.flush();
                                        if (progressDialog.isShowing()) {
                                            progressDialog.dismiss();
                                        }
                                    }
                                } catch (IOException e) {
                                    Log.d("IOException", e.getClass().getSimpleName() + ": " + e.getMessage());
                                    e.printStackTrace();
                                }
                                break;
                            case 1:
                                try {
                                    BufferedWriter w = new BufferedWriter(new OutputStreamWriter(MyApplication.OS_CURRENT));
                                    w.write(AddMessageConstants.NOT_ACCEPT_FRIEND_REQUEST);
                                    w.write(user_id + "!!" + friend_id);
                                    w.flush();
                                    // remove item in list view
                                    MyApplication.LIST_FRIENDS_REQUEST.remove(numSelectedInListView);
                                    mListViewFriendRequest.setAdapter(friendRequestAdapter);
                                } catch (IOException e) {
                                    Log.d("IOException", e.getClass().getSimpleName() + ": " + e.getMessage());
                                    e.printStackTrace();
                                }
                                break;
                            case 2:
                                CommonUtil.dialogNotify(getActivity(), "Name:\t\t\t" + fullName + "\nEmail:\t\t\t" + email
                                        + "\nBirthday:\t" + birthday + "\nGender:\t\t" + strGender + "\nStatus:\t\t" + status);
                                break;
                            default:
                                break;
                        }
                    }
                });
                dialog.show();
                return false;
            }
        });
        rlAddFriend = (RelativeLayout) view.findViewById(R.id.layout_add_friend);
        rlFriendsRequest = (RelativeLayout) view.findViewById(R.id.layout_friends_request);
        edtSearch = (EditText) view.findViewById(R.id.edtSearch);
        edtSearch.setText("thino1@gmail.com");
        edtSearch.setFocusable(true);
        edtSearch.setOnEditorActionListener(new TextView.OnEditorActionListener() {

            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {

                if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                    ((InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE)).hideSoftInputFromWindow(
                            getActivity().getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
                    processSearchFriends();
                    return true;
                }
                return false;
            }
        });
        btnAddFriend = (Button) view.findViewById(R.id.btnAddFriend);
        btnFriendRequest = (Button) view.findViewById(R.id.btnFriendRequests);

        btnAddFriend.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
                if (!isPressAddFriendButton) {
                    isPressAddFriendButton = true;
                    isPressFriendsRequestButton = false;
                    rlAddFriend.setVisibility(View.VISIBLE);
                    rlFriendsRequest.setVisibility(View.GONE);
                } else {
                    isPressAddFriendButton = false;
                    isPressFriendsRequestButton = false;
                    rlAddFriend.setVisibility(View.GONE);
                }
            }
        });

        btnFriendRequest.setOnClickListener(new OnClickListener() {

            public void onClick(View v) {
                if (!isPressFriendsRequestButton) {
                    isPressAddFriendButton = false;
                    isPressFriendsRequestButton = true;
                    rlAddFriend.setVisibility(View.GONE);
                    rlFriendsRequest.setVisibility(View.VISIBLE);
                } else {
                    isPressAddFriendButton = false;
                    isPressFriendsRequestButton = false;
                    rlFriendsRequest.setVisibility(View.GONE);
                }
            }
        });
        btnSearchFriends = (Button) view.findViewById(R.id.btnSearchFriends);
        btnSearchFriends.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
                CommonUtil.hideVirtualKeyboard(v);
                processSearchFriends();
            }
        });
    }

    Timer timer;

    private void processSearchFriends() {
        String strSearch = edtSearch.getText().toString().trim();
        if ("".equals(strSearch) == true) {
            Toast.makeText(getActivity(), "Nothing for search! You must enter data!", Toast.LENGTH_LONG).show();
        } else {
            progressDialog = ProgressDialog.show(getActivity(), "", "Searching friends...");

            new Thread(new Runnable() {
                public void run() {
                    Message message = toastHandler.obtainMessage();
                    Bundle data = new Bundle();
                    try {
                        BufferedWriter w = new BufferedWriter(new OutputStreamWriter(MyApplication.OS_CURRENT));
                        w.write(AddMessageConstants.SEARCH_FRIENDS);
                        w.write(MyApplication.USER_CURRENT.getId() + "!!" + edtSearch.getText().toString().trim());
                        w.flush();
                        /*
                         * timer = new Timer(); timer.schedule(new TimerTask() {
                         * 
                         * @Override public void run() {
                         * 
                         * } }, 10000);
                         */
                    } catch (SocketTimeoutException e) {
                        /*
                         * Message msg = toastHandler.obtainMessage(2);
                         * toastHandler.sendMessage(msg); return;
                         */
                        data.putString("ERROR", DisplayConstants.DIS_CONNECT_SERVER_FAIL);
                    } catch (UnknownHostException e) {
                        Log.d("UnknownHostException", e.getClass().getSimpleName() + ": " + e.getMessage());
                        e.printStackTrace();
                        data.putString("ERROR", e.getMessage());
                    } catch (IOException e) {
                        Log.d("IOException", e.getClass().getSimpleName() + ": " + e.getMessage());
                        e.printStackTrace();
                        data.putString("ERROR", e.getMessage());
                    } catch (Exception e) {
                        Log.d("Exception", e.getClass().getSimpleName() + ": " + e.getMessage());
                        e.printStackTrace();
                        data.putString("ERROR", e.getMessage());
                    }
                    message.setData(data);
                    message.what = 10;
                    toastHandler.sendMessage(message);

                }
            }).start();
        }
    }

    @Override
    public void addListenners() {
        // nothing
    }

    /** Show Toast message */
    private Handler toastHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            if (msg.what == 0) {
                Toast.makeText(getActivity(), DisplayConstants.DIS_SEARCH_NO_RESULT, Toast.LENGTH_LONG).show();
            } else if (msg.what == 1) {
                Toast.makeText(getActivity(), DisplayConstants.DIS_SEARCH_HAVE_RESULTS, Toast.LENGTH_LONG).show();
                mListViewFriendSearch.setAdapter(new SearchFriendsAdapter(getActivity(), users));
                mListViewFriendSearch.setOnItemLongClickListener(new OnItemLongClickListener() {
                    public boolean onItemLongClick(AdapterView<?> adapter, View v, int position, long id) {
                        numSelectedInListView = position;
                        AlertDialog.Builder dialog = new AlertDialog.Builder(getActivity());
                        dialog.setItems(new String[] { "Add this friend", "View Profile" }, new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int which) {
                                user_id = MyApplication.USER_CURRENT.getId();
                                friend_id = ((User) mListViewFriendSearch.getAdapter().getItem(numSelectedInListView)).getId();
                                fullName = ((User) mListViewFriendSearch.getAdapter().getItem(numSelectedInListView)).getFullName();
                                email = ((User) mListViewFriendSearch.getAdapter().getItem(numSelectedInListView)).getEmail();
                                birthday = CommonUtil.dateToString(((User) mListViewFriendSearch.getAdapter()
                                        .getItem(numSelectedInListView)).getBirthday());
                                gender = ((User) mListViewFriendSearch.getAdapter().getItem(numSelectedInListView)).getGender();
                                strGender = gender == 1 ? "Male" : "Female";
                                status = ((User) mListViewFriendSearch.getAdapter().getItem(numSelectedInListView)).getStatus();
                                last_status = ((User) mListViewFriendSearch.getAdapter().getItem(numSelectedInListView)).getLastStatus();
                                if ("null".equals(status)) {
                                    status = "No status";
                                }
                                switch (which) {
                                    case 0:
                                        progressDialog = ProgressDialog.show(getActivity(), "", "Adding friend...");
                                        try {
                                            BufferedWriter w = new BufferedWriter(new OutputStreamWriter(MyApplication.OS_CURRENT));
                                            if (user_id == friend_id) {
                                                Message msg = toastHandler.obtainMessage(3);
                                                toastHandler.sendMessage(msg);
                                            } else {
                                                w.write(AddMessageConstants.ADD_FRIEND);
                                                w.write(user_id + "!!" + friend_id);
                                                w.flush();
                                                if (progressDialog.isShowing()) {
                                                    progressDialog.dismiss();
                                                }
                                            }
                                        } catch (IOException e) {
                                            Log.d("IOException", e.getClass().getSimpleName() + ": " + e.getMessage());
                                            e.printStackTrace();
                                        }
                                        break;
                                    case 1:
                                        CommonUtil.dialogNotify(getActivity(), "Name:\t\t\t" + fullName + "\nEmail:\t\t\t" + email
                                                + "\nBirthday:\t" + birthday + "\nGender:\t\t" + strGender + "\nStatus:\t\t" + status);
                                        break;
                                    default:
                                        break;
                                }
                            }
                        });
                        dialog.show();
                        return false;
                    }
                });
            } else if (msg.what == 2) {
                if (progressDialog.isShowing()) {
                    progressDialog.dismiss();
                }
                CommonUtil.dialogNotify(getActivity(), DisplayConstants.DIS_CONNECT_SERVER_FAIL);
            } else if (msg.what == 3) {
                Toast.makeText(getActivity(), DisplayConstants.DIS_ADD_FRIEND_FAIL, Toast.LENGTH_LONG).show();
            } else if (msg.what == 4) {
                Toast.makeText(getActivity(), DisplayConstants.DIS_ADDED_FRIEND, Toast.LENGTH_LONG).show();
            } else if (msg.what == 5) {
                Toast.makeText(getActivity(), DisplayConstants.DIS_EXISTED_FRIEND, Toast.LENGTH_LONG).show();
            } else if (msg.what == 6) {
                friendRequestAdapter = new SearchFriendsAdapter(getActivity(), MyApplication.LIST_FRIENDS_REQUEST);
                mListViewFriendRequest.setAdapter(friendRequestAdapter);
                Toast.makeText(getActivity(), "Hava a friend request!", Toast.LENGTH_LONG).show();
            } else if (msg.what == 7) {
                Toast.makeText(getActivity(), DisplayConstants.DIS_ACCEPT_FRIEND_REQUEST_FAIL, Toast.LENGTH_LONG).show();
            } else if (msg.what == 8) {
                Toast.makeText(getActivity(), DisplayConstants.DIS_ACCEPT_FRIEND_REQUEST_SUCCESS, Toast.LENGTH_LONG).show();
                User user = new User();
                user.setId(friend_id);
                user.setFullName(fullName);
                user.setAvatar("http://profile.ak.fbcdn.net/hprofile-ak-ash3/c72.31.388.388/s160x160/69242_445766122158689_209300158_n.jpg");
                user.setEmail(email);
                user.setBirthday(birthday);
                user.setGender(gender);
                user.setStatus(status);
                user.setLastStatus(last_status);
                Intent intent = new Intent();
                intent.setAction("ADD_FRIEND");
                intent.putExtra("user_add", user);
                getActivity().sendBroadcast(intent);
                // romove item accepted
                // friendRequest.remove(numSelectedInListView);
                MyApplication.LIST_FRIENDS_REQUEST.remove(numSelectedInListView);
                mListViewFriendRequest.setAdapter(friendRequestAdapter);
            } else if (msg.what == 9) {
                Toast.makeText(getActivity(), DisplayConstants.DIS_HAS_SEND_FRIEND_REQUEST, Toast.LENGTH_LONG).show();
            } else if (msg.what == 10) {
                if (progressDialog.isShowing()) {
                    progressDialog.dismiss();
                }
                if (msg.getData() != null) {
                    Bundle data = msg.getData();
                    if (data.containsKey("ERROR")) {
                        Toast.makeText(getActivity(), data.getString("ERROR"), Toast.LENGTH_LONG).show();
                    }
                }
            }
        }
    };

    /**
     * receiver message broadcast
     * 
     * @author vuvt
     * 
     */
    private class MessageBroadCastReceiver extends BroadcastReceiver {
        @SuppressWarnings("unchecked")
        @Override
        public void onReceive(Context context, Intent intent) {
            if ("SEARCH_FRIENDS".equals(intent.getAction())) {
                int num = Integer.parseInt(intent.getBundleExtra("bundle").getString("msg"));
                if (num == 1) {
                    users = new ArrayList<User>();
                    users = (ArrayList<User>) intent.getBundleExtra("bundle").getSerializable("users_search");
                }
                Message msg = toastHandler.obtainMessage(num);
                toastHandler.sendMessage(msg);
            } else if ("NOTIFY_FRIEND_REQUEST".equals(intent.getAction())) {
                int num = Integer.parseInt(intent.getBundleExtra("bundle").getString("msg"));
                if (num == 6) {
                    MyApplication.LIST_FRIENDS_REQUEST.add((User) intent.getBundleExtra("bundle").getSerializable("friend_request"));
                }
                Message msg = toastHandler.obtainMessage(num);
                toastHandler.sendMessage(msg);
            } else if ("ACCEPT_FRIEND_REQUEST".equals(intent.getAction())) {
                int num = Integer.parseInt(intent.getStringExtra("msg"));
                Message msg = toastHandler.obtainMessage(num);
                toastHandler.sendMessage(msg);
            }
        }
    }
}
